﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GameStateManagement;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using SuperRyoninRPG.Controller;
using SuperRyoninRPG.Main;

namespace SuperRyoninRPG.Characters
{
	public class Comment
	{
		private const int NamePosition = 6;
		private int textCounter = 0;
		private float charTime = 0f;
		private float nextCharTime = 0.1f;

		public string Name { get; set; }
		public string Body { get; set; }

		public bool IsKeyUp { get; set; }

		private Texture2D background;

		private ScreenManager screenManager;

		public Comment(ScreenManager screenManager, string name, string body)
		{
			this.screenManager = screenManager;
			this.Name = name;
			this.Body = body;
			LoadContent();
		}

		private void LoadContent()
		{
			this.background = this.screenManager.Game.Content.Load<Texture2D>("Images/Comment");
		}

		public void Update(
			GameTime gameTime,
			KeyboardState keyboardState,
			GamePadState gamePadState,
			TouchCollection touchState,
			AccelerometerState accelState,
			DisplayOrientation orientation)
		{
			var elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
			charTime += elapsed;
			if (charTime > nextCharTime)
			{
				charTime = 0f;
				textCounter ++;
				if (textCounter > this.Body.Length)
				{
					textCounter = this.Body.Length;
				}
			}
		}

		/// <summary>
		///     アニメーション表示された
		///     プレイヤーを描画します。
		/// </summary>
		public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
		{

			var viewPortWidth = screenManager.ScreenWidth;
			float parcentage = 0.7f;
			float width = viewPortWidth * parcentage;
			float x = viewPortWidth * (1.0f-parcentage)/2.0f;
			float size = width / this.background.Width;
			var display = new Rectangle((int)x, 0, (int)width,
				(int)(this.background.Height * size));
			
			spriteBatch.Draw(this.background, display, Color.White);
			DrawString(gameTime, spriteBatch, new Vector2((int)x, 0), size);
		}

		private void DrawString(GameTime gameTime, SpriteBatch spriteBatch,Vector2 basePosition,float size)
		{
			var font = this.screenManager.Font;
			Vector2 position = basePosition + new Vector2(NamePosition * size, NamePosition * size);
			var scale = size * 0.2f;

			spriteBatch.DrawString(font, this.Name, position, Color.White, 0f, Vector2.Zero, scale, SpriteEffects.None, 0f);
			string body = this.Body.Substring(0, this.textCounter);
			Vector2 bodyPosition = position + new Vector2(0, font.LineSpacing * scale * 1.5f);
			spriteBatch.DrawString(font, body, bodyPosition, Color.White, 0f, Vector2.Zero, scale, SpriteEffects.None, 0f);
		}
	}
}
